package aures.plugins;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.python.core.PyFunction;

import aures.ui.AuresStdio;;


public class sysPlugin {

	static public final String HOOK_ON_RECEIVE  = "HOOK_ON_RECEIVE";
	static public final String HOOK_AFTER_PARSE = "HOOK_AFTER_PARSE";
	static public final String HOOK_ON_GAME		= "HOOK_ON_GAME";
	
	private static Map<String, List<Hook>> hooks;
	private static Map<String, Plugin> plugins;
	private static AuresStdio server;
	
	static public void initialize (){
		if (hooks == null){
			plugins = new HashMap<String, Plugin>();
			hooks = new HashMap<String, List<Hook>>();
			hooks.put(HOOK_ON_RECEIVE, new ArrayList<Hook>());
			hooks.put(HOOK_AFTER_PARSE, new ArrayList<Hook>());
			hooks.put(HOOK_ON_GAME, new ArrayList<Hook>());
		}
	}
	
	static public void loadPlugins (String mod_path){
		Plugin plugin = null;
		
		File dir = new File(mod_path);
		String[] list = dir.list();

		for (String s:list){
			File script = new File(mod_path + s);
			if (script.isFile()){
				System.out.println("Loading " + s);
				try{
					plugin = new Plugin(mod_path + s);
					
					plugin.init();
					plugins.put(plugin.getName(), plugin);
				
				}catch (Exception e){
					sysPlugin.printErr(plugin.getFilename() + "\n" + e.toString());
				}
			}
		}
	}
	
	static public void cleanPlugins () throws Exception{
		Set<String> keys = plugins.keySet();
		
		for (String s:keys){
			Plugin p = plugins.get(s);
			p.clean();
		}
		
		plugins.clear();
	}
	
	static public void cleanPlugin (String name) throws Exception{

		Plugin p = plugins.get(name);
		if (p != null){
			p.clean();
			plugins.remove(name);
		}
	}
	
	static public void addHook (Plugin p, String name, String fname){
		List<Hook> lis = hooks.get(name);
		PyFunction function = p.getPyFunction(fname);
		
		lis.add(new Hook(function));
	}
	
	static public void removeHook (String name, String fname){
		List<Hook> lis = hooks.get(name);
		for (Hook hk : lis){
			if (hk.getFunction().__name__.equalsIgnoreCase(fname)){
				lis.remove(hk);
				break;
			}
		}
	}
	
	static public void runHooks (String name){
		List<Hook> lis = hooks.get(name);
		for (Hook hk : lis){
			hk.run();
		}
	}
	
	static public void print (String message){
		server.print(message);
	}
	
	static public void printErr (String message){
		server.printError(message);
	}

	public static AuresStdio getStdio() {
		return server;
	}

	public static void setStdio(AuresStdio ser) {
		server = ser;
	}
	
	public static void dumpPlugins (){
		Set<String> keys = plugins.keySet();
		
		for (String s:keys){
			Plugin p = plugins.get(s);
			sysPlugin.print("Plugin " + p.getName() + "\n");
		}

	}
}
